<?php
defined('IN_APP') or die('Access Denied');
class gateway_memcached extends Memcached
{
    public function __construct($host, $port, $id = 'story_pool')
    {
        parent::__construct($id);
        if (!parent::addServer($host, $port))
        {
            throw new Exception("Could not connect memcached server $host:$port."."\n".
                                 'Error code: '.parent::getResultCode()."\n".
                                 ' Error message: '.parent::getResultMessage()
                                 );
        }
        parent::setOption(Memcached::OPT_BINARY_PROTOCOL, true);
    }
    public function getError()
    {
        return 'Error code: '.$this->getResultCode()."\n".
               'Error message: '.$this->getResultMessage()
               ;
    }
    public function get($key, $update_callback = NULL, &$cas_token = NULL, &$udf_flags = NULL)
    {
        $data = parent::get($key, NULL);
        $result = $this->getResultCode();
        switch ($result)
        {
            case Memcached::RES_NOTFOUND:
                if ($update_callback)
                {
                    $data = call_user_func($update_callback, $this, $key);
                }else{
                    $data = false;
                }
                $data['from'] = 'origin';
                return($data);
            case Memcached::RES_SUCCESS:
                $data['from'] = 'cached';
                return($data);
            default:
                throw new memcached_excpetion($this);
        }
    }
    public function set($key, $data, $expiration = NULL, $udf_flags = NULL)
    {
        if ($expiration)
        {
            $expiration = time() + $expiration;
        }
        parent::set($key, $data, $expiration);
    }
    public function update($key, $url, $expiration = 0)
    {
        $data = fetch_source($url);
        if ($data['status'] == 200)
            {
                $this->set($key, $data, $expiration);
            }
        return $data;
    }
    
}
